package com.bijava.config;

import com.bijava.entity.OrderEvent;
import com.bijava.factory.OrderEventFactory;
import com.bijava.handler.OrderEventHandler;
import com.bijava.producer.OrderEventProducer;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

/**
 * @author swifty
 * @version 1.0.0
 * @since 2024-12-30
 */
@Configuration
public class DisruptorConfig {
    @Bean
    public Disruptor<OrderEvent> disruptor() {
        OrderEventFactory factory = new OrderEventFactory();
        int bufferSize = 2048 * 1024; // RingBuffer 大小

        Disruptor<OrderEvent> disruptor = new Disruptor<>(factory, bufferSize, Executors.defaultThreadFactory());
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        new Disruptor<>(factory, bufferSize, Executors.defaultThreadFactory(), ProducerType.SINGLE, new BlockingWaitStrategy());

        // 绑定事件处理器
        disruptor.handleEventsWith(new OrderEventHandler());
        disruptor.start();
        return disruptor;
    }

    @Bean
    public OrderEventProducer orderEventProducer(Disruptor<OrderEvent> disruptor) {
        return new OrderEventProducer(disruptor.getRingBuffer());
    }
}
